package cn.tedu.baking.controller;

import cn.tedu.baking.commom.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Slf4j
@RestController
@RequestMapping("/v1")
public class UploadController {
    @Value("${file-path}")
    private String dirPath;
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //得到文件的初始文件名
        String fileName=file.getOriginalFilename();
        //得到后缀 从最后一个,的位置截取到最后 xxxx.jpg
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;//得到唯一文件名 UUID.randomUUID()得到唯一标识符
        //准备文件夹路径 d:/files/2023/10/18/xxx.jpg
        String dirPath="d:/files";
        SimpleDateFormat dataFormat=new SimpleDateFormat("/yyy/MM/dd/");
        String dataPath= dataFormat.format(new Date());
        File dirFile=new File(dirPath+dataPath);
        if (!dirFile.exists()){//如果文件夹不存在
            dirFile.mkdirs();//创建文件夹
        }
        //把文件保存到指定路径 d:/files/2023/10/18/xxxxx.jpg  //抛出异常
        // http://localhost:8080/2023/10/18/xxxxx.jpg
        file.transferTo(new File(dirPath+dataPath+fileName));
        return JsonResult.ok(dataPath+fileName);
    }

    // http://localhost:8080/v1/remove?url=xxxx
    @PostMapping("remove")
    public JsonResult remove(String url){
        log.debug("url = "+url);
        new File(dirPath+url).delete();
        return JsonResult.ok();
    }

}
